from django.http import HttpResponseRedirect
from django.shortcuts import render
from com.user.sign_in_controller import is_sign_in
from smart_monitor.models import Communicator as c_db_m
from my_models.terminal_model import Terminal as t_m


class Terminal(object):
    def __init__(self, request, *args):
        self.request = request
        self.communicator_id = args[0][0]

    def run(self):
        sign_in, user_name = is_sign_in(self.request)
        if not sign_in:
            return HttpResponseRedirect("/user/sign_in")
        if not self.communicator_id:
            return render(self.request, "404.html", {})
        try:
            communicator = c_db_m.objects.get(id=self.communicator_id)
        except Exception as e:
            return render(self.request, "404.html", {})
        terminals_set = communicator.com.all()
        terminals = []
        for terminal_obj in terminals_set:
            terminals.append(t_m(terminal_obj.terminal_id,
                                 terminal_obj.id,
                                 terminal_obj.terminal_info,
                                 terminal_obj.terminal_state,
                                 communicator.communicator_id,
                                 communicator.user_name_id))

        data_set = {
            "terminals": terminals,
            "user_name": user_name,
        }
        return render(self.request, "terminal_console.html", data_set)
